/**
 * www.easyplatform.cn ©2016
 */
package cn.easyplatform.studio.cmd.identity;

import cn.easyplatform.studio.StudioException;
import cn.easyplatform.studio.dao.DaoException;
import cn.easyplatform.studio.interceptor.Command;
import cn.easyplatform.studio.interceptor.CommandContext;
import cn.easyplatform.studio.vos.FieldVo;
import cn.easyplatform.studio.vos.RoleVo;
import cn.easyplatform.type.FieldType;

import java.util.ArrayList;
import java.util.List;

/**
 * @author <a href="mailto:shiny_vc@163.com">陈云亮</a> <br/>
 * @since 2.0.0 <br/>
 */
public class UpdateStudioRoleCmd implements Command<Boolean> {

    private RoleVo role;

    /**
     * @param role
     */
    public UpdateStudioRoleCmd(RoleVo role) {
        this.role = role;
    }

    @Override
    public Boolean execute(CommandContext cc) {
        List<FieldVo> params = new ArrayList<FieldVo>();
        try {
            cc.beginTx();
            if (role.getCode() == 'D') {
                params.add(new FieldVo(FieldType.VARCHAR, role.getId()));
                params.add(new FieldVo(FieldType.VARCHAR, cc.getProject().getId()));
                cc.getIdentityDao().update(
                        "delete from ep_role_info where roleId=? and projectId=?", params);
            } else if (role.getCode() == 'C') {
                params.add(new FieldVo(FieldType.VARCHAR, role.getId()));
                params.add(new FieldVo(FieldType.VARCHAR, cc.getProject().getId()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getName()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getDesp()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getImage()));
                cc.getIdentityDao()
                        .update("insert into ep_role_info(roleId,projectId,name,desp,permissions) values (?,?,?,?,?)",
                                params);
            } else {
                params.add(new FieldVo(FieldType.VARCHAR, role.getName()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getDesp()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getImage()));
                params.add(new FieldVo(FieldType.VARCHAR, role.getId()));
                params.add(new FieldVo(FieldType.VARCHAR, cc.getProject().getId()));
                cc.getIdentityDao()
                        .update("update ep_role_info set name=?,desp=?,permissions=? where roleId=? and projectId=?",
                                params);
            }
            cc.commitTx();
            return true;
        } catch (Exception ex) {
            cc.rollbackTx();
            if (ex instanceof DaoException)
                throw (DaoException) ex;
            throw new StudioException("UpdateStudioRoleCmd:" + ex.getMessage());
        } finally {
            cc.closeTx();
        }
    }
}
